#!/usr/bin/env python3
"""
初始化示例标签数据的脚本
"""
import json
import sys
import os
import uuid

# 添加server目录到路径中，以便导入模块
sys.path.append(os.path.join(os.path.dirname(__file__), 'server'))

from server.app.db import session_scope, Label, init_db

def load_sample_labels():
    """加载示例标签数据"""
    # 初始化数据库
    init_db()
    
    # 加载示例数据
    with open('sample_labels.json', 'r', encoding='utf-8') as f:
        sample_labels = json.load(f)
    
    with session_scope() as session:
        # 清空现有标签（可选）
        print("清空现有标签...")
        session.query(Label).delete()
        
        # 第一遍：创建所有父级标签
        parent_map = {}  # name -> id mapping
        
        print("创建父级标签...")
        for label_data in sample_labels:
            if 'parent_name' not in label_data:  # 父级标签
                label = Label(
                    id=uuid.uuid4(),
                    name=label_data['name'],
                    color=label_data['color'],
                    description=label_data.get('description'),
                    sort=label_data.get('sort', 0)
                )
                session.add(label)
                session.flush()  # 确保获得ID
                parent_map[label_data['name']] = label.id
                print(f"  ✅ 创建父级标签: {label.name} (ID: {label.id})")
        
        # 第二遍：创建子级标签
        print("创建子级标签...")
        for label_data in sample_labels:
            if 'parent_name' in label_data:  # 子级标签
                parent_id = parent_map.get(label_data['parent_name'])
                if parent_id:
                    label = Label(
                        id=uuid.uuid4(),
                        parent_id=parent_id,
                        name=label_data['name'],
                        color=label_data['color'],
                        description=label_data.get('description'),
                        sort=label_data.get('sort', 0)
                    )
                    session.add(label)
                    print(f"  ✅ 创建子级标签: {label.name} -> {label_data['parent_name']} (ID: {label.id})")
                else:
                    print(f"  ❌ 找不到父级标签: {label_data['parent_name']}")
        
        print(f"\n🎉 成功加载 {len(sample_labels)} 个示例标签!")

if __name__ == "__main__":
    try:
        load_sample_labels()
    except Exception as e:
        print(f"❌ 加载示例数据时出错: {e}")
        sys.exit(1)
